<!--
 * @Author: mayijun
 * @Date: 2022-06-02 09:22:58
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-14 14:59:59
-->

<template>
  <PortalNavbar
    :logo="state.logo"
    :logoMenus="userPlatform"
    @logoMenuClick="onLogoMenuClick"
    :activeMenu="state.activeMenu"
    :menus="menusData"
    @menuItemClick="onMenuClick"
    :user="user"
    @userDropdownSelect="onUserDropdownSelect"
    @logout="onLogout"
    id="navBarComponent"
  />
</template>
<script lang="ts" setup>
// @ts-ignore
// eslint-disable-next-line import/no-unresolved
import PortalNavbar from '@dangojs/portal-navbar';
import '@dangojs/portal-navbar/dist/css/index.css';
import { computed, onMounted, PropType, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { clearCookie, backPreviousSys } from '@/utils/util';
import { IConfig } from './types';
import _ from 'lodash';
import http from '@/utils/http';
import { Message } from '@arco-design/web-vue';

const props = defineProps({
  config: {
    type: Object as PropType<IConfig>,
    default: () => ({
      showBackSelectPlatform: false,
      showCollapse: true,
      isCollapse: false,
      massage: 0,
      userInfo: {
        userName: '--',
        userAccount: '--'
      },
      permission: [],
      operateoption: []
    })
  }
});

const emit = defineEmits(['changeApp']);

const route = useRoute();

//登录用户
const user = ref({
  name: '',
  email: '',
  avatar: ''
});

const userCenter = ref();
const userPlatform = ref<any[]>([]);

const state = reactive({
  logo: 'https://image.parligerly.com/protal-svg/logo-hom.svg',
  activeMenu: ''
});
//处理头部菜单，只显示第一级
const menusData: any = computed(() => {
  let menusDataList: any[] = [];
  if (
    props.config &&
    props.config.permission &&
    props.config.permission[0].childrens
  ) {
    menusDataList = _.cloneDeep(props.config.permission[0].childrens);
    menusDataList.map((item) => {
      item.childrens = null;
      if (route.path.indexOf(item.resourceLink) != -1) {
        state.activeMenu = item.resourceCode;
      }
    });
  }

  return menusDataList;
});

const onLogoMenuClick = (data: any) => {
  const { path } = data;
  if (path) {
    window.location.href = path;
  } else {
    Message.warning('未设置链接');
  }
};

const onMenuClick = (key: string, data: any) => {
  if (
    props.config &&
    props.config.permission &&
    props.config.permission[0].childrens
  ) {
    let menusDataList = _.cloneDeep(props.config.permission[0].childrens);
    let index = menusDataList.findIndex(
      (item: any) => item.resourceCode == key
    );
    //设置激活菜单
    state.activeMenu = key;
    emit('changeApp', data.resourceLink, index);
  }
};

//退出登录
const onLogout = () => {
  clearCookie('access-token');
  backPreviousSys('');
};

const hideTenant = () => {
  const navBarComp = document.getElementById('navBarComponent');
  if (navBarComp) {
    (
      navBarComp.querySelector(
        '.a-portal-navbar-right> .arco-select'
      ) as HTMLDivElement
    ).style.display = 'none';
  }
};

const hideMessageCenter = () => {
  const navBarComp = document.getElementById('navBarComponent');
  if (navBarComp) {
    (
      navBarComp.querySelector(
        '.a-portal-navbar-right> div > div:nth-child(2)'
      ) as HTMLDivElement
    ).style.display = 'none';
  }
};
const hideHelpCenter = () => {
  const navBarComp = document.getElementById('navBarComponent');
  if (navBarComp) {
    (
      navBarComp.querySelector(
        '.a-portal-navbar-right> div > div:nth-child(3)'
      ) as HTMLDivElement
    ).style.display = 'none';
  }
};

const setUserPortal = () => {
  const { userName: name, email, icon: avatar } = props.config.userInfo as any;
  user.value = {
    name,
    email,
    avatar:
      avatar ??
      'http://wework.qpic.cn/bizmail/dWKchAQwABekEOW9HvOjXFynpjVcpCgTDubHoy3JJuHb6yc1ubw7Ow/0'
  };
};

// 查询用户中心地址
const fetchUCenterURL = () => {
  return fetchInfoFromUms(['ucenter'], 'system');
};

// 查询平台菜单
const fetchPlatform = () => {
  return http.post('/api/ums/user/listPlatformResByUser', {});
};

// 通过 ums 查询字典项数据
const fetchInfoFromUms = (entryKeys: any[], typeKey: string) => {
  return http.post('/api/ums/dictEntry/listByEntryKeys', {
    entryKeys,
    typeKey
  });
};

const setUCenterURL = () => {
  fetchUCenterURL().then((res: any) => {
    if (res.success) {
      if (Array.isArray(res.data) && res.data.length > 0) {
        userCenter.value = res.data[0]?.path ?? '';
      }
    } else {
      Message.error(res.message);
    }
  });
};

const onUserDropdownSelect = (type: string) => {
  if (type === 'userCenter') {
    location.href = userCenter.value;
  }
};

const fetchPlatformData = () => {
  fetchPlatform().then((res: any) => {
    if (res.success) {
      const formatPlatform = [
        {
          name: '全部',
          type: '1',
          list: (res.data ?? []).map((i: any) => {
            return {
              icon: 'https://image.parligerly.com/protal-svg/mark.svg',
              logo: 'https://image.parligerly.com/protal-svg/mark-logo.svg',
              title: i.systemName,
              desc: i.systemCode,
              path: i.path
            };
          })
        }
      ];
      userPlatform.value = formatPlatform;
    } else {
      Message.error(res.message);
    }
  });
};
watch(() => route.path,(newPath, oldPath) => {
  console.log('route: ', newPath, oldPath)
  console.log('menusData: ', menusData.value)
 if (menusData.value?.length) {
  const activeMenu = menusData.value.find((item:any) => route.path.indexOf(item.resourceLink) != -1);
  state.activeMenu = activeMenu.resourceCode
  console.log('state.activeMenu: ', state.activeMenu)
 }
},{immediate: true});
onMounted(() => {
  fetchPlatformData();
  setUCenterURL();
  setUserPortal();
  hideTenant();
  hideMessageCenter();
  hideHelpCenter();
});
</script>
<style lang="scss">
.a-portal-navbar-logo-menu {
  min-width: 60px;
}
.a-portal-navbar {
  position: relative;
}
</style>